package org.brisling.duties.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.domain.RetDomain;
import org.brisling.base.service.AbstractBaseService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.duties.domain.DutiesInquiry;
import org.brisling.duties.domain.DutiesStatistic;
import org.brisling.duties.queryService.QueryDutiesinquiryService;
import org.brisling.duties.queryService.QueryDutiesstatisticService;
import org.brisling.duties.repository.DutiesInquiryRepo;
import org.brisling.duties.service.base.BaseDutiesFlowService;
import org.brisling.sysman.domain.JobRole;
import org.brisling.sysman.queryService.QueryJobRoleService;
import org.brisling.sysman.queryService.QueryPermissionService;
import org.brisling.workflow.domain.VOHistoric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping("/dutiesInquiry")
/**
 * 用戶后台服務service
 * @Author : jackson wang
 * @Date   : 2015年6月8日 下午4:18:01
 * @version: 1.0
 */
public class DutiesInquiryService extends BaseDutiesFlowService<DutiesInquiry>{
	
	
	private static Logger logger = LoggerFactory.getLogger(DutiesInquiryService.class);
	
	@Autowired
	QueryPermissionService queryPermissionService;
			
	@SuppressWarnings("unused")
	@Autowired
	private DutiesInquiryRepo baseFlowRepo;	
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	@Autowired
	private QueryJobRoleService qryJobRoleService;
	
	
	@Autowired
	private QueryDutiesstatisticService qryDutiesstatisticService;
	public DutiesInquiryService(){
		this.moduleName = ConstSysParam.MODULE_DUTIES_INQUIRY;
		this.clazz = DutiesInquiry.class;
	}
	
	/**
	 * 获取业务主页面 
	 * @return
	 */
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return getBizMainPage();
	}
	
	/**
	 * 获取业务编辑页面
	 * @return
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return getBizEditPage();
	}
	
	/**
	 * 返回缺陷记录流程实例id的执行记录
	 * @param procInstId 流程实例id
	 * @return List<HistoricTaskInstance> 流程实例执行记录
	 */
	@RequestMapping("/flowHistorics.action")
	public List<VOHistoric> getHistoricByProcInstId(@RequestParam(value="flowInstId",required=false) String procInstId){
		return super.getHistoricByProcInstId(procInstId);
	}
	
	/**
	 * 返回缺陷记录流程实例id的执行记录
	 * @param procInstId 流程实例id
	 * @return List<HistoricTaskInstance> 流程实例执行记录
	 */
	@RequestMapping("/flowHistoricsListDomain.action")
	public ListDomain<VOHistoric> getBugHistoricListDomainByProcInstId(@RequestParam(value="flowInstId",required=false) String procInstId){
		return super.getHistoricListDomainByProcInstId(procInstId);
	}
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @param flowtype 流程状态,null:全部,3:当前用户已签收,2::当前用户可签收,1:执行中,0:已结束
	 * @return
	 */
	
	@RequestMapping("/flowListDomain.action")
	public ListDomain<DutiesInquiry> getListDomain(
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="sort",required=false) String sort,
			@RequestParam(value="flowtype",required=false) String flowtype,
			@RequestParam(value="fullBizcode",required=false) String fullBizcode){
		
			if(flowtype==null)
				return super.getListDomain(page, rows, sort, fullBizcode);
			else{
				switch(flowtype){
				
				case "0":
					return getFinishiedListDomain(page, rows, sort, fullBizcode);
					
				default:
					return null;
				}
			}
			
			
	}
	
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getFinishedListDomain.action")
	public ListDomain<DutiesInquiry> getFinishiedListDomain(
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="sort",required=false) String sort,
			@RequestParam(value="fullBizcode",required=false) String fullBizcode){
		
		
			return super.getPagedFinishedFlowRows(page, rows, sort, fullBizcode);
			
	}
	
	
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/flowList.action")
	public List<DutiesInquiry> getPagedFlowRows(
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="sort",required=false) String sort,			
			@RequestParam(value="fullBizcode",required=false) String fullBizcode
			){		
		
		return super.getPagedFlowRows(page, rows, sort, fullBizcode);			
	}
	
	
	
	@RequestMapping("/flowDel.action")
	public RetDomain delRow(@RequestParam(value="id",required=false) Long id,@RequestParam(value="ids",required=false) String ids){
		RetDomain domain = new RetDomain();
		if(id!=null){
			if(super.deleteTask(id, null)){
				domain.setSuccessMsg("200");
				return domain;
			}else{
				domain.setErrorMsg("500");
				return domain;
			}
		}else{
			if(ids!=null){
				Integer count =super.deleteTaskList(ids, null);
				domain.setMsg("删除 " + count + " 条记录成功!");
			}
		}
		
		return domain;
		
	}
	
	/**
	 * 保存缺陷记录
	 * @param id
	 */
	
	@RequestMapping("/flowSave.action")
	public DutiesInquiry save(@RequestBody String body){      
		//将前端传递的参数转化为Domain
		DutiesInquiry obj = bodyToObj(body, DutiesInquiry.class);
		//判断是否传递后转化的Domain是否为空
		if(obj!=null){   
			//如果业务编码为空值
			if(obj.getBizno()==null || obj.getBizno().trim().length()<=0){
				//生成设置Domian业务编码
				obj.setBizno(qryService.generateBizno());  
			}
		}
		//保存生成流程信息的Domain实体
		DutiesInquiry inquiry = super.saveFlowEntity(shiroSecurityService.getCurrentUserid().toString(),obj);
		//判断保存后的Domain是否为空
		if((inquiry!=null) && (inquiry.getId()!=null)){
			//查询并返回保存后的数据Domian
			inquiry = qryService.getOne(inquiry.getId());
		}
		return inquiry;
	}
	
	/**
	 * 自动保存职能监控质询记录
	 * @param id
	 */
	
	public DutiesInquiry autoSave(String userid,DutiesInquiry obj){
			
		DutiesInquiry domain= this.saveFlowEntity(userid,obj);
		if((domain!=null) && (domain.getId()!=null)){
			domain = qryService.getOne(domain.getId());
		}
		return domain;
	}
	
	/**
	 * 签收记录
	 * @param flowInstId	流程实例id
	 * @param flowTaskId	流程节点id
	 * @param signInfo		签收信息
	 * @param body
	 * @return
	 */
	@RequestMapping("/flowSign.action")
	public ListDomain<Object> saveSingInfo(@RequestBody String body){
		
		return this.saveSignInfo(shiroSecurityService.getCurrentUserid().toString(), body);
	}
	
	/**
	 * 流程执行
	 * @param flowInstId	流程实例id
	 * @param flowTaskId	流程任务节点id
	 * @param signInfo		签收信息
	 * @param body
	 * @return
	 */
	@Autowired
	private QueryDutiesinquiryService qryService;
	
	@RequestMapping("/flowTaskComplete.action")
	public String completeTask(@RequestBody String body){
		DutiesInquiry domain =this.save(body);
		if(domain!=null){			
			return super.completeTaskAndCandidateByEntity(
					shiroSecurityService.getCurrentUserid().toString(),
					domain, 
					"签收");
		}
		
		return "500";		
	}
	
	
	/**
	 * 自动发送任务方法
	 * @param userId	任务发送人员id
	 * @param domain	发送的业务单据实体
	 * @return
	 */
	public String completeTask(String userId,DutiesInquiry domain){
		domain =this.autoSave(userId,domain);
		
		if(domain!=null && userId!=null){			
			return super.completeTaskAndCandidateByEntity(
					userId,domain,"签收");
		}
		
		return "500";
		
	}
	
	@RequestMapping("/flowSendback.action")
	public RetDomain saveSendbackTask(@RequestBody String body){
		DutiesInquiry domain =this.save(body);
		if(domain!=null){
			return super.saveSendBack(
					shiroSecurityService.getCurrentUserid().toString(), 
					domain, null, null);
			
		}
		RetDomain ret = new RetDomain();
		ret.setErrorMsg("业务保存失败");
		return ret;
	}
	
	public void countAndInsert(){
		String Bizcode="dutiesInquiry";//业务编码
		String bizcode=queryPermissionService.getBizFlowConfig(Bizcode).getFullBizcode();
		String flowid=queryPermissionService.getBizFlowConfig(Bizcode).getFlowid();
		//查询抗菌药物使用强度异常数据
		//List<DutiesDomain> lists=qryDutieService.getWindowAntiDose();
		List<DutiesStatistic>  lists=qryDutiesstatisticService.getAPPListDomain("2237");
		
				
		Map<Long,JobRole> jobRoleMap= qryJobRoleService.getDeptJobRoles("科主任");
		
//		Map<String,JobRole> jobRoleMap= qryJobRoleService.getDeptNameJobRoles("科主任");
		
		if(lists!=null&&bizcode!=null&&flowid!=null){
			for(DutiesStatistic a: lists){
				String thisdate=DateUtil.date2JsonStr(new Date());//获取时间
				thisdate = thisdate ==null?"":thisdate.substring(0,10);
				
				DutiesInquiry m = new DutiesInquiry();
				m.setLitigant_deptid(a.getDoct_depart_code());
				m.setFlowid(flowid);//
				m.setFullBizcode(bizcode);//
				m.setInquiry_date(new Date());
				
				m.setInquiry_item("办理超时");
				m.setInquiry_item_code("34");
				m.setInquiry_reason("截止"+thisdate+",有事项未能及时办理完成");
				m.setSummy_count(a.getSumary_matter());
				m.setLitigant_deptname(a.getDept_name());
				
				Long deptid = a.getDoct_depart_code();
//				String _deptName = a.getDept_name();
//				if(_deptName!=null){
//					int index = _deptName.indexOf("(");
//					if(index>=0){
//						_deptName = _deptName.substring(0,index);
//					}
//					
//					index = _deptName.indexOf("（");
//					if(index>=0){
//						_deptName = _deptName.substring(0,index);
//					}
//				}
//				if(jobRoleMap.containsKey(_deptName)){
//					m.setLitigant_name(jobRoleMap.get(_deptName).getUsername());
//					m.setLitigant_id(LongUtil.getLongValue(jobRoleMap.get(_deptName).getUserid(),null));
//				}
				
				//岗位角色临时变量
				JobRole jr = null;
				
				//是否执行质询标志
				boolean canInquiry = false;
				
				//判断科室管理岗人员是否存在
				if(deptid!=null && jobRoleMap.containsKey(deptid)){
					jr = jobRoleMap.get(deptid);
					if(jr!=null){
						canInquiry = true;
					}
				}
				
				//根据质询标志位判断是否执行质询
				if(canInquiry){
					Long uid = LongUtil.getLongValue(jr.getUserid(), null);
					m.setLitigant_id(uid);
					m.setLitigant_name(jr.getUsername());
					//设置异常实体信息
					String id =SysConfig.getConfig("inquiryUserId");
					this.completeTask(id, m);
				}else{
					logger.info("=====================  can not find deptid: " + deptid +" managers job user =======================");
				}
				
			}
	   }
  }
	
	
}
